#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>

#define NUM 10000

int tickets=NUM;
pthread_mutex_t lock;

void *getticks(void *arg)
{
  int number=(int)arg;
  while(1)
  {
         pthread_mutex_lock(&lock);
      if(tickets>0)
      {
         usleep(100);
         printf("thread[ %d ]抢票:  %d\n",number,tickets--);
         pthread_mutex_unlock(&lock);
         usleep(10000);
      }
      else
      {
         pthread_mutex_unlock(&lock);
         usleep(10000);
        break;
      }
  }
}
int main()
{
  //创建线程
  pthread_t tid[5];
  pthread_mutex_init(&lock,NULL);
  for(int i=0 ; i<5 ; i++)
  {
    pthread_create(&tid[i],NULL,getticks,(void*)i);
  }
  //线程等待
  for(int i=0 ; i<5 ; i++)
  {
    pthread_join(tid[i],NULL);
  }
  pthread_mutex_destroy(&lock);
  return 0;
}
